/*
 * Atomic Predicates for Transformers
 * 
 * Copyright (c) 2015 UNIVERSITY OF TEXAS AUSTIN. All rights reserved. Developed
 * by: HONGKUN YANG and SIMON S. LAM http://www.cs.utexas.edu/users/lam/NRL/
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * with the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimers.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimers in the documentation
 * and/or other materials provided with the distribution.
 * 
 * 3. Neither the name of the UNIVERSITY OF TEXAS AUSTIN nor the names of the
 * developers may be used to endorse or promote products derived from this
 * Software without specific prior written permission.
 * 
 * 4. Any report or paper describing results derived from using any part of this
 * Software must cite the following publication of the developers: Hongkun Yang
 * and Simon S. Lam, Scalable Verification of Networks With Packet Transformers
 * Using Atomic Predicates, IEEE/ACM Transactions on Networking, October 2017,
 * Volume 25, No. 5, pages 2900-2915 (first published as IEEE Early Access
 * Article, July 2017, Digital Object Identifier: 10.1109/TNET.2017.2720172).
 * 
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH
 * THE SOFTWARE.
 */
package transformer;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

import common.PositionTuple;

public class TestMPLS2 {

    public static void test_MPLS(int tunnel_number) throws IOException
    {
        Network i2 = new Network("i2", true);

        ArrayList<ArrayList<Network.MPLSPathUnit>> paths = i2.extract_mpls_path();
        for(int i = 0; i < paths.size() - tunnel_number; i ++)
        {
            i2.remove_tunnel(paths.get(i));
        }

        HashSet<PositionTuple> allpts = i2.getallactiveports();
        String outputfolder = "mpls_i2/";
        PrintWriter pw = new PrintWriter(new File(outputfolder + tunnel_number+"tunnels"));
        //StateTransferI2Run.compute_trees(i2, allpts, pw);
        StateTransferI2Run.compute_trees_anypkt(i2, allpts, pw);
        pw.close();

    }

    public static void complete_tunnel() throws IOException
    {

        Network i2 = new Network("i2", true);
        // router and its neighbors
        HashMap<String, HashSet<String>> neighbors = new HashMap<String, HashSet<String>>();
        for (PositionTuple pt : i2.topology.keySet())
        {
            if(!neighbors.containsKey(pt.getDeviceName()))
            {
                neighbors.put(pt.getDeviceName(), new HashSet<String>());
            }

            for(PositionTuple pt2 : i2.LinkTransfer(pt))
            {
                neighbors.get(pt.getDeviceName()).add(pt2.getDeviceName());
            }

            //System.out.println(neighbors.get(pt.getDeviceName()));
        }


        ArrayList<ArrayList<Network.MPLSPathUnit>> paths = i2.extract_mpls_path();

        Set<String> all_routers = neighbors.keySet();
        int cur_label_base = 1000;
        int offset = 1000;
        int resv_label = 3;
        int tunnel_cnt = 0;

        PrintWriter pw = new PrintWriter(new File("i2_tunnels"));

        for(ArrayList<Network.MPLSPathUnit> path : paths)
        {
            HashSet<String> used = new HashSet<String> ();
            ArrayList<String> completed_path = new ArrayList<String> ();

            boolean entry_flag = false;
            boolean exit_flag = false;
            boolean dest_flag = false;

            for (int i = 0; i < path.size(); i ++)
            {
                Network.MPLSPathUnit mpu = path.get(i);
                used.add(mpu.device_name);

                // add entry
                if(i == 0)
                {
                    for(String r : neighbors.get(mpu.device_name))
                    {
                        if(!used.contains(r))
                        {
                            completed_path.add(r);
                            used.add(r);

                            completed_path.add(Integer.toString(cur_label_base + i - 1));

                            entry_flag = true;

                            break;
                        }
                    }
                    if(!entry_flag)
                    {
                        break;
                    }
                }

                completed_path.add(mpu.device_name);
                completed_path.add(Integer.toString(cur_label_base+i));

                // add exit
                if(i == path.size() - 1)
                {
                    // set exit label
                    completed_path.set(completed_path.size()-1, Integer.toString(resv_label));

                    for(String r : neighbors.get(mpu.device_name))
                    {
                        if(!used.contains(r))
                        {
                            completed_path.add(r);
                            used.add(r);

                            exit_flag = true;
                            break;
                        }
                    }
                    if(!exit_flag)
                    {
                        break;
                    }

                    // add destination
                    for(String r : all_routers)
                    {
                        if(!used.contains(r))
                        {
                            completed_path.add(r);
                            used.add(r);

                            dest_flag = true;

                            break;
                        }
                    }

                    if(!dest_flag)
                    {
                        break;
                    }else
                    {
                        // reaching here means that we complete a MPLS path in success
                        if(completed_path.size() > 6)
                        {
                            for(String s : completed_path)
                            {
                                pw.print(s + " ");
                            }
                            pw.println();


                            tunnel_cnt ++;
                        }
                    }
                }
            }

            cur_label_base += offset;   
        }

        System.out.println(tunnel_cnt + " tunnels");
        pw.close();
    }

    public static void main (String[] args) throws IOException
    {
        complete_tunnel();
    }

}
